package com.dreem.prototype.deepclone;

import java.io.*;

/**
 * @program: DesignParrtern
 * @description: 深拷贝
 * @author: Peng
 * @create: 2021-01-28  12:09
 **/
public class DeepProtoType implements Serializable, Cloneable {

    public String name; // 基本数据类型
    public DeepCloneableTarget deepCloneableTarget; // 引用数据类型

    public DeepProtoType(){

    }

    // 方式1： 深拷贝，使用clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        // 这里完成对对基本数据类型的（属性）和String的拷贝
        deep = super.clone();
        // 对引用类型的属性，进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }

    // 方式2：深拷贝，通过对象的序列化实现（推荐）
    public Object deepClone(){
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType deepClone = (DeepProtoType)ois.readObject();
            return deepClone;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            if(bos != null || bis != null){
                try {
                    ois.close();
                    bis.close();
                    oos.close();
                    bos.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
